#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
临时搜索修复 - 使用固定视频ID来测试功能
"""

import asyncio
import sys
import os
from datetime import datetime

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from crawlers.hybrid.hybrid_crawler import HybridCrawler
from utils.export_manager import export_manager

async def temp_search_with_fixed_videos(keyword: str, count: int = 3):
    """
    临时解决方案：使用固定的视频ID来模拟搜索结果
    """
    print(f"临时搜索解决方案: 关键词={keyword}, 数量={count}")
    
    # 一些测试用的视频ID（从之前成功的测试中获取）
    test_video_ids = [
        "7536808376698998075",  # 测试视频1
        "7536112491195583803",  # 美食视频1 
        "7535021526421228846",  # 美食视频2
        "7535017965524241690",  # 美食视频3
        "7535795623502449956"   # 美食视频4
    ]
    
    # 根据关键词选择合适的视频ID
    if "美食" in keyword or "食" in keyword:
        selected_ids = test_video_ids[1:4]  # 选择美食相关的
    else:
        selected_ids = test_video_ids[:count]  # 选择前几个
    
    # 限制数量
    selected_ids = selected_ids[:count]
    
    try:
        # 初始化混合解析器
        hybrid_crawler = HybridCrawler()
        complete_videos = []
        
        for video_id in selected_ids:
            try:
                # 构造视频URL
                video_url = f"https://www.douyin.com/video/{video_id}"
                
                print(f"解析视频: {video_id}")
                
                # 获取视频详细信息
                video_data = await hybrid_crawler.hybrid_parsing_single_video(video_url)
                
                if video_data:
                    # 整合完整数据（简化版，不获取评论）
                    complete_video_data = {
                        "aweme_id": video_id,
                        "desc": video_data.get('desc', ''),
                        "author": {
                            "nickname": video_data.get('author', {}).get('nickname', ''),
                            "sec_user_id": video_data.get('author', {}).get('sec_user_id', '')
                        },
                        "statistics": {
                            "digg_count": video_data.get('statistics', {}).get('digg_count', 0),
                            "comment_count": video_data.get('statistics', {}).get('comment_count', 0),
                            "share_count": video_data.get('statistics', {}).get('share_count', 0),
                            "play_count": video_data.get('statistics', {}).get('play_count', 0)
                        },
                        "video_urls": {
                            # 正常观看链接 - 抖音原页面
                            "watch_url": video_url,
                            # 无水印下载链接 - 通过项目API下载，避免403错误
                            "download_url": f"http://127.0.0.1:8080/api/download?url={video_url}&with_watermark=false"
                        },
                        "api_urls": {
                            "full": f"http://127.0.0.1:8080/api/hybrid/video_data?url={video_url}&minimal=false",
                            "minimal": f"http://127.0.0.1:8080/api/hybrid/video_data?url={video_url}&minimal=true"
                        },
                        "comments": [],  # 临时解决方案中不获取评论
                        "create_time": video_data.get('create_time', 0)
                    }
                    
                    complete_videos.append(complete_video_data)
                    print(f"  成功: {video_data.get('desc', '')[:30]}...")
                    
            except Exception as e:
                print(f"解析视频 {video_id} 失败: {str(e)}")
                continue
        
        # 构造返回数据
        result = {
            "search_info": {
                "keyword": keyword,
                "total_found": len(complete_videos),
                "search_time": datetime.now().isoformat(),
                "note": "临时解决方案：使用固定视频ID代替搜索API"
            },
            "videos": complete_videos
        }
        
        print(f"临时搜索完成: 找到{len(complete_videos)}个视频")
        return result
        
    except Exception as e:
        print(f"临时搜索失败: {str(e)}")
        return None

async def test_temp_search():
    """测试临时搜索解决方案"""
    print("测试临时搜索解决方案...")
    
    keywords = ["青岛", "美食", "测试"]
    
    for keyword in keywords:
        print(f"\n{'='*50}")
        print(f"测试关键词: {keyword}")
        print('='*50)
        
        try:
            # 使用临时搜索
            search_data = await temp_search_with_fixed_videos(keyword, 2)
            
            if search_data and len(search_data.get('videos', [])) > 0:
                videos = search_data.get('videos', [])
                print(f"成功找到 {len(videos)} 个视频")
                
                # 显示视频信息
                for i, video in enumerate(videos, 1):
                    print(f"  视频{i}: {video.get('desc', '')[:40]}...")
                    urls = video.get('video_urls', {})
                    print(f"    观看: {urls.get('watch_url', '无')}")
                    print(f"    下载: {urls.get('download_url', '无')}")
                
                # 尝试导出
                json_path = export_manager.export_to_json(search_data, f"temp_{keyword}")
                csv_path = export_manager.export_to_csv(search_data, f"temp_{keyword}")
                
                print(f"导出成功:")
                print(f"  JSON: {json_path}")
                print(f"  CSV: {csv_path}")
                
            else:
                print("未找到视频")
                
        except Exception as e:
            print(f"测试失败: {str(e)}")
            import traceback
            traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(test_temp_search())